package com.csdj.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.csdj.reggie.commcn.BaseContext;
import com.csdj.reggie.commcn.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {

    public static final AntPathMatcher PATH_MATCHER=new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

//        转型
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        HttpServletRequest request=(HttpServletRequest) servletRequest;




//        1.获取本次请求的uri
        String uri=request.getRequestURI();
//        日志输出
        log.info("拦截到请求：{}",uri);

        String[] uris=new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/sendMsg",
                "/user/login"
        };

//        2.判断本次请求是否需要处理
        Boolean checks = check(uris, uri);

//        3.如果不需要处理，则直接放行
        if (checks){
            log.info("本次请求{}不需要处理",request.getRequestURI());
            filterChain.doFilter(request,response);
            return;
        }
//        4_1.判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录，用户名id为：{}",request.getSession().getAttribute("employee"));

            Long id=(Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(id);

            filterChain.doFilter(request,response);
            return;
        }

        //        4_2.判断移动端登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user")!=null){
            log.info("用户已登录，用户名id为：{}",request.getSession().getAttribute("user"));

            Long userId=(Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
//        5.如果未登录则返回登录结果
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    public Boolean check(String[] uris,String uri){
        for (String s : uris) {
            boolean match = PATH_MATCHER.match(s, uri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
